<?php

namespace app\api\controller;

use app\common\model\ChatGroupContent as ChatGroupContentModel;
use app\common\model\UserCirclePrice as UserCirclePriceModel;
use app\common\model\ChatGroup as ChatGroupModel;
use app\common\model\ChatRoom as ChatRoomModel;
use app\common\model\Config as ConfigModel;
use app\common\model\UserCircle;
use app\common\model\User;
use app\api\common\Wxpay;
use app\util\CurlRequest;
use think\Db;

class Notify
{
    /**
     * 微信订单支付回调
     */
    public function wxNotify()
    {
        $data = file_get_contents('php://input');
        $apiv3_private_key = ConfigModel::getConfigValue("wx_pay_private_key");
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $apiv3_private_key);
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state']=='SUCCESS'){
                $order_no=$orderData['out_trade_no']; //商户订单号
                $transaction_id=$orderData['transaction_id']; //微信订单号
                $table = substr($order_no,0,1);
                if($table=="F"){//发帖置顶
                    return $this->orderNotify($order_no,$transaction_id);
                }elseif($table=="Z"){//置顶帖子
                    return $this->topNotify($order_no,$transaction_id);
                }elseif ($table=="B"){//缴纳保证金
                    return $this->marginNotify($order_no,$transaction_id);
                }elseif ($table=="L"){//群聊保证金
                    return $this->groupChatNotify($order_no,$transaction_id);
                }elseif ($table=="R"){//商家认证费
                    return $this->certificationFee($order_no,$transaction_id);
                }elseif ($table=="X"){//商家认证续费
                    return $this->renewalNotify($order_no,$transaction_id);
                }
            }
        }
        return json_encode(['code' => 'ERROR', 'message' =>'no']);
    }


    /**
     * 发帖支付回调逻辑
     * @param string $order_no 商户订单号
     * @param string $transaction_id 微信订单号
     */
    private function orderNotify($order_no,$transaction_id)
    {
        // 启动事务
        Db::startTrans();
        try{
            /*业务处理*/
            $info = UserCirclePriceModel::where("order_no",$order_no)->find();
            if (empty($info) || $info->ispay!= '0'){
                return json_encode(['code' => 'ERROR', 'message' =>'no']);
            }
            $circle_data = [];
            $circle_data["index_top"] = $info["index_top"];
            $circle_data["cate_top"] = $info["cate_top"];
            $time = time();
            $index_top = $info["index_top"];
            if($index_top){
                $circle_data["index_top_paytime"] = $time;
            }
            $cate_top = $info["cate_top"];
            if($cate_top){
                $circle_data["cate_top_paytime"] = $time;
            }
//            if($index_top){
//                $index_top_time = $time;
//                $index_top_endtime = strtotime("+$index_top days");
//            }else{
//                $index_top_endtime = "";
//                $index_top_time = "";
//            }
//            if($index_top){
//                $cate_top_endtime = strtotime("+$cate_top days");
//                $cate_top_time = $time;
//            }else{
//                $cate_top_endtime = "";
//                $cate_top_time = "";
//            }
            $circle_data["index_top_price"] = $info["index_top_price"];
            $circle_data["cate_top_price"] = $info["cate_top_price"];
            $circle_data["user_circle_price_id"] = $info['id'];
//            $circle_data["index_top_time"] = $index_top_time;
//            $circle_data["index_top_endtime"] = $index_top_endtime;
//            $circle_data["cate_top_time"] = $cate_top_time;
//            $circle_data["cate_top_endtime"] = $cate_top_endtime;
            UserCircle::where("id",$info["circle_id"])->update($circle_data);
            $info->ispay = 1;
            $info->pay_time = time();
            $info->transaction_id = $transaction_id;
            $info->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['code' => 'ERROR', 'message' =>'no']);
        }
        return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
    }

    /**
     * 置顶支付回调逻辑
     * @param string $order_no 商户订单号
     * @param string $transaction_id 微信订单号
     */
    public function topNotify($order_no,$transaction_id)
    {
        // 启动事务
        Db::startTrans();
        try{
            /*业务处理*/
            $info = UserCirclePriceModel::where("order_no",$order_no)->find();
            if (empty($info) || $info->ispay!= '0'){
                return json_encode(['code' => 'ERROR', 'message' =>'no']);
            }
            $circle_arr = Db::name("user_circle")->where("id","IN",$info['circle_id'])->field("id,authen,index_top,index_top_time,index_top_endtime,cate_top,cate_top_time,cate_top_endtime")->select();
            foreach ($circle_arr as &$value){
                $circle_data = [];
                $circle_data["index_top"] = $info["index_top"];
                $circle_data["cate_top"] = $info["cate_top"];
                $time = time();
                $index_top = $info["index_top"];
                if($index_top){
                    if($value['index_top_endtime'] > $time){
                        $index_top_time = $value['index_top_time'];
                        $index_top_endtime = $value['index_top_endtime'] + ($index_top*86400);
                    }else{
                        $index_top_time = $time;
                        $index_top_endtime = strtotime("+$index_top days");
                    }
                }else{
                    $index_top_endtime = "";
                    $index_top_time = "";
                }
                $cate_top = $info["cate_top"];
                if($cate_top){
                    if($value['cate_top_endtime'] > $time){
                        $cate_top_time = $value['cate_top_time'];
                        $cate_top_endtime = $value['cate_top_endtime'] + ($cate_top*86400);
                    }else{
                        $cate_top_endtime = strtotime("+$cate_top days");
                        $cate_top_time = $time;
                    }
                }else{
                    $cate_top_endtime = "";
                    $cate_top_time = "";
                }
                $circle_data["index_top_price"] = $info["index_top_price"];
                $circle_data["cate_top_price"] = $info["cate_top_price"];
                $circle_data["index_top_time"] = $index_top_time;
                $circle_data["index_top_endtime"] = $index_top_endtime;
                $circle_data["cate_top_time"] = $cate_top_time;
                $circle_data["cate_top_endtime"] = $cate_top_endtime;;
                UserCircle::where("id",$value["id"])->update($circle_data);
            }
            UserCircle::where("id","IN",$info["circle_id"])->update($circle_data);
            $info->ispay = 1;
            $info->pay_time = time();
            $info->transaction_id = $transaction_id;
            $info->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['code' => 'ERROR', 'message' =>'no']);
        }
        return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
    }

    /**
     * 保证金支付回调逻辑
     * @param string $order_no 商户订单号
     * @param string $transaction_id 微信订单号
     */
    public function marginNotify($order_no,$transaction_id)
    {
        // 启动事务
        Db::startTrans();
        try{
            /*业务处理*/
            $info = Db::name("user_deposit")->where("order_no",$order_no)->find();
            if (empty($info) || $info['ispay']!= '0'){
                return json_encode(['code' => 'ERROR', 'message' =>'no']);
            }
            $user_data = [];
            $user_data["deposit_price"] = $info["price"];
            User::where("user_id",$info["user_id"])->update($user_data);
            $info_data = [];
            $info_data['ispay'] = 1;
            $info_data['pay_time'] = time();
            $info_data['transaction_id'] = $transaction_id;
            Db::name("user_deposit")->where("order_no",$order_no)->update($info_data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['code' => 'ERROR', 'message' =>'no']);
        }
        return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
    }

    /**
     * 群聊保证金支付回调逻辑
     * @param string $order_no 商户订单号
     * @param string $transaction_id 微信订单号
     */
    public function groupChatNotify($order_no,$transaction_id)
    {
        // 启动事务
        Db::startTrans();
        try{
            /*业务处理*/
            $info = Db::name("chat_group_user")->where("order_no",$order_no)->find();
            if (empty($info) || $info['ispay']!= '0'){
                return json_encode(['code' => 'ERROR', 'message' =>'no']);
            }
            $info_data = [];
            $info_data['ispay'] = 1;
            $info_data['pay_time'] = time();
            $info_data['transaction_id'] = $transaction_id;
            Db::name("chat_group_user")->where("order_no",$order_no)->update($info_data);
            ChatRoomModel::where(["user_id"=>$info["user_id"],"to_id"=>$info["group_id"],"group_type"=>2])->update(["is_margin"=>1]);
            $userInfo =  User::where("user_id",$info["user_id"])->field("identification,username")->find();
            $group_info = ChatGroupModel::get($info['group_id']);
            if($userInfo->identification){
                ChatRoomModel::groupAddUser($group_info['h_id'],[$userInfo->identification]);
            }
//            if($group_info["user_ids"]){
//                // 将user_ids和接收到的值都转换成数组
//                $user_ids_array = explode(',', $group_info['user_ids']);
//                $received_values_array = explode(',', $info['user_id']);
//                // 使用array_merge函数将两个数组合并
//                $merged_userids = array_merge($user_ids_array, $received_values_array);
//
//                // 使用array_unique函数移除重复的值
//                $filtered_userids = array_unique($merged_userids);
//
//                // 将最终的数组转换回逗号分隔的字符串
//                $user_ids = implode(',', $filtered_userids);
//                $group_info->user_ids = $user_ids;
//                $group_info->save();
//            }else{
//                $group_info->user_ids = $info['user_id'];
//                $group_info->save();
//            }
            ChatRoomModel::where(["user_id"=>$info['user_id'],"group_room"=>$info['group_id'],"group_type"=>2])->update(["is_margin"=>1]);
            $group_id = $info['group_id'];
            $where = "to_id = {$group_id}";
            $where.= " AND information_id = '0'";
            $where.= " AND group_type = '2'";
            $room_id_arr = ChatRoomModel::where($where)->column("id");
            if($room_id_arr){
                $room_id_str = implode(",",$room_id_arr);
            }else{
                $room_id_str = "";
            }
            $room_info = ChatRoomModel::where($where)->find();
            if(!$room_info->group_room){
                ChatRoomModel::where($room_info)->update(["group_room"=>$group_id]);
            }
            $group_identification = User::where("user_id",$group_info['user_id'])->value("identification");
            $group_data = [];
            $group_data['group_id'] = $group_id;
            $group_data['user_id'] = $group_info['user_id'];
            $group_data['room_ids'] = $room_id_str;
            $group_data['content'] = "欢迎".$userInfo->username."加入群聊";
            $group_data['type'] = 1;
            $group_data['add_time'] = time();
            $msg_id = Db::name("chat_group_content")->insertGetId($group_data);
            ChatRoomModel::where(["group_room"=>$group_id,"is_margin"=>1,"group_type"=>2])->setInc("number",1);
            //消息中心
            $list = ChatRoomModel::chat_content_info($group_info['user_id'],$group_id,2);
            //$is_margin = ChatRoomModel::where(["group_room"=>$group_id,"is_margin"=>1])->column("user_id");
            $is_margin = 1;
            $list['is_margin'] = $is_margin;
            $list['b_user_id'] = $info['user_id'];
            $list['type'] = 13;
            $list["group_room"] = $group_id;
            $list['content'] = $group_data['content'];
            $list['last_time'] = getChatTimeStr(time());
            //聊天内容
            $info = ChatGroupContentModel::get_content_info($msg_id,$room_info->id);
            $info['type'] = 13;
            $info['is_margin'] = $is_margin;
            $info["group_room"] = $group_id;
            $content = [
                "list" => $list,
                "info" => $info,
            ];
            //ChatRoomModel::sendToUser($group_identification,$userInfo->identification,$content);
            ChatRoomModel::sendToGroup($group_identification,$group_info['h_id'],$content);
            ChatRoomModel::where($where)->update(["content"=>$group_data['content'],"group_room"=>$group_id,"last_time"=>time()]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['code' => 'ERROR', 'message' =>'no']);
        }
        return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
    }

    /**
     * 商家认证费支付回调逻辑
     * @param string $order_no 商户订单号
     * @param string $transaction_id 微信订单号
     */
    public function certificationFee($order_no,$transaction_id)
    {
        // 启动事务
        Db::startTrans();
        try{
            /*业务处理*/
            $info = Db::name("user_certification")->where("order_no",$order_no)->find();
            if (empty($info) || $info['ispay']!= '0'){
                return json_encode(['code' => 'ERROR', 'message' =>'no']);
            }
            $user_data = [];
            $user_data["authen"] = 2;
            User::where("user_id",$info["user_id"])->update($user_data);
            $info_data = [];
            $info_data['ispay'] = 1;
            $info_data['pay_time'] = time();
            $info_data['transaction_id'] = $transaction_id;
            Db::name("user_certification")->where("order_no",$order_no)->update($info_data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['code' => 'ERROR', 'message' =>'no']);
        }
        return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
    }

    /**
     * 商家续费支付回调逻辑
     * @param string $order_no 商户订单号
     * @param string $transaction_id 微信订单号
     */
    public function renewalNotify($order_no,$transaction_id)
    {
        // 启动事务
        Db::startTrans();
        try{
            /*业务处理*/
            $info = Db::name("user_certification")->where("order_no",$order_no)->find();
            if (empty($info) || $info['ispay']!= '0'){
                return json_encode(['code' => 'ERROR', 'message' =>'no']);
            }
            $user = User::get($info['user_id']);
            $user_data = [];
            $user_data["authen"] = 3;
            if($user->end_time){
                $end_time = strtotime($user->end_time)+($info["month"]*86400*30);
                $user_data['end_time'] = $end_time;
            }else{
                $end_time = time()+($info["month"]*86400*30);
                $user_data['end_time'] =$end_time;
            }
            User::where("user_id",$info["user_id"])->update($user_data);
            $info_data = [];
            $info_data['ispay'] = 1;
            $info_data['pay_time'] = time();
            $info_data['transaction_id'] = $transaction_id;
            Db::name("user_certification")->where("order_no",$order_no)->update($info_data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['code' => 'ERROR', 'message' =>'no']);
        }
        return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
    }

    //退款回调地址
    public function refund_notify()
    {
        $notifiedData = file_get_contents('php://input');
        $apiv3_private_key = ConfigModel::getConfigValue("wx_pay_private_key");
        $data = json_decode($notifiedData, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $apiv3_private_key);
            Db::name("test")->where("id",1)->update(["attachfile"=>$orderData]);
            $orderData = json_decode($orderData, true);
            $out_refund_no=$orderData['out_refund_no']; //商户退款单号
            $table = substr($out_refund_no,0,1);
            if($table=="F"){//发帖置顶
                $order_info = UserCirclePriceModel::where('order_no',$out_refund_no)->find();
            }elseif($table=="Z"){//置顶帖子
                $order_info = UserCirclePriceModel::where('order_no',$out_refund_no)->find();;
            }elseif ($table=="B"){//商家保证金
                $order_info = Db::name("user_deposit")->where('order_no',$out_refund_no)->find();
            }elseif ($table=="L"){//群聊保证金
                $order_info = Db::name("chat_group_user")->where('order_no',$out_refund_no)->find();
                $update_data = [];
                $update_data["is_tui"] = 1;
                if(isset($orderData['success_time'])){
                    $update_data["tui_time"] = strtotime($orderData['success_time']);
                }else{
                    $update_data["tui_time"] = time();
                }
                $res = Db::name("chat_group_user")->where("id",$order_info['id'])->update($update_data);
                if ($res){
                    return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
                }
            }elseif ($table=="R"){//取消认证
                $order_info = Db::name("user_certification")->where('order_no',$out_refund_no)->find();
                $update_data = [];
                $update_data["tui_order_no"] = $orderData['refund_id'];
                $update_data["istui"] = 1;
                $update_data["reason"] = "取消认证";
                if(isset($orderData['success_time'])){
                    $update_data["authen_time"] = strtotime($orderData['success_time']);
                }else{
                    $update_data["authen_time"] = time();
                }
                $res = Db::name("user_certification")->where("id",$order_info['id'])->update($update_data);
                if ($res){
                    return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
                }
            }
//            if ($order_info['refund_status']==4){
//                $update_data = [
//                    'refund_time'=>$orderData['success_time'],
//                    'refund_money'=>number_format($orderData['amount']['refund']/100,2),
//                    'refund_processing_status'=>$orderData['refund_status'],
//                    'user_received_account'=>$orderData['user_received_account'],
//                    'refund_data_raw'=>json_encode($orderData,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)
//                ];
//                if ($orderData['refund_status']=='SUCCESS'){
//                    $update_data['refund_status'] = 5;
//                }else{
//                    $update_data['refund_status'] = 6;
//                }
//                $res = Db::name("order")->where("id",$order_info['id'])->update($update_data);
//                if ($res){
//                    return json_encode(['code' => 'SUCCESS', 'message' =>'ok']);
//                }
//            }
        }
        return json_encode(['code' => 'ERROR', 'message' =>'no']);
    }

    /**
     * 小程序消息推送
     */
    public function messagePush()
    {
//        $echoStr = $_GET["echostr"];
//        $signature = $_GET["signature"];
//        $timestamp = $_GET["timestamp"];
//        $nonce = $_GET["nonce"];
//        $token = '7vk8HfvoHMknT7BgfbEWwnK9bdE7R5QZ';
//        $tmpArr = array($token, $timestamp, $nonce);
//        sort($tmpArr);
//        $tmpStr = implode($tmpArr);
//        $tmpStr = sha1($tmpStr);
//        if ($tmpStr == $signature) {
//            ob_clean(); //增加的一行
//            echo $echoStr;
//            exit;
//        }
//        {
//            "ToUserName":"gh_687b7a7ffb17",
//            "FromUserName":"oQ3to5Hn34hGs_dG6UZ7zVF6x7ok",
//            "CreateTime":1706258095,
//            "MsgType":"event",
//            "Event":"trade_manage_order_settlement",
//            "transaction_id":"4200002097202401269125738559",
//            "merchant_id":"1664963027",
//            "sub_merchant_id":"0",
//            "merchant_trade_no":"117062581565031",
//            "pay_time":1706258025,
//            "shipped_time":1706258095,
//            "estimated_settlement_time":1707122095
//        }
        header("Content-type: text/html; charset=utf-8");
        $postStr = file_get_contents('php://input');
        $postArr = json_decode($postStr,true);
        //收货
        if ($postArr["Event"] === "trade_manage_order_settlement"){
            if (isset($postArr["confirm_receive_method"]) && ($postArr["confirm_receive_method"] == 1 || $postArr["confirm_receive_method"] == 2)){
                $merchant_trade_no = $postArr["merchant_trade_no"];
                $transaction_id = $postArr["transaction_id"];
                $info = Db::name("order")->where("order_no = '$merchant_trade_no' AND transaction_id = '$transaction_id'")->find();
                if (!empty($info) && $info["status"] == 2){
                    Db::name("order")->where("id = {$info["id"]}")->update(["status"=>3,"receiving_time"=>time()]);
                }
            }else{
                //小程序后台发货
                $wx_pay = new Wxpay();
                $access_token_data = $wx_pay->getAccessToken();
                $access_token = $access_token_data["data"]["access_token"];
                $url = "https://api.weixin.qq.com/wxa/sec/order/get_order?access_token=".$access_token;
                $data = [
                    "transaction_id" => $postArr["transaction_id"],
                    "merchant_id" => $postArr["merchant_id"],
                    "merchant_trade_no" => $postArr["merchant_trade_no"],
                ];
                $data = json_encode($data,JSON_UNESCAPED_UNICODE);
                $result = CurlRequest::sendCurlPost($url,$data);
                $arr = json_decode($result,true);
                if($arr["errcode"] == 0){
                    $merchant_trade_no = $arr['order']["merchant_trade_no"];
                    $transaction_id = $arr['order']["transaction_id"];
                    $logistics = $arr['order']['shipping']['shipping_list'];
                    foreach ($logistics as $value) {
                        $field = "id,status,refund_type";
                        $info = Db::name("order")->where("order_no = '$merchant_trade_no' AND transaction_id = '$transaction_id'")->field($field)->find();
                        if (!empty($info) && $info["status"] == 1 && $info["refund_type"] == 0){
                            $express_company = Db::name("delivery")->where("delivery_id",$value["express_company"])->value("delivery_name");
                            $update_order_data['status'] = 2;
                            $update_order_data['delivery_time'] = time();
                            $update_order_data['express_company'] = $express_company;
                            $update_order_data['tracking_number'] = $value['tracking_no'];
                            Db::name("order")->where("id = {$info["id"]}")->update($update_order_data);
                        }
                    }
                }
            }
        }
        echo "success";
    }



}